import React, { PureComponent } from 'react'
import { View, ScrollView } from '@tarojs/components'
import Taro, { getCurrentInstance } from '@tarojs/taro'
import { getThemeStyle, timestampToTime } from '@/utils'
import FilterBlock from './comps/filterblock'
import { ORDER_LIST_CANCEL_REASON } from '@/consts'
import { withPager, withBackToTop } from '@/hocs'
import { SpLoading, SpNote, SpOrderItem, SpTips, SpToast, SpNavBar } from '@/components'
import { SelectInput, Tabbar, PageActionButtons } from '@/components/sp-page-components'
import { calculateTimestamp } from '@/utils/time'
import { classNames } from '@/utils'
import api from '@/api'
import { connect } from 'react-redux'
import './index.scss'
import S from '@/spx'
import { Tracker } from '@/service'

// import PullToRefresh from 'pulltorefreshjs';
import { PullToRefresh, InfiniteScroll } from 'antd-mobile'

@connect(({ planSelection }) => ({
  planSelection: planSelection.activeShop
}))
@withPager
@withBackToTop
export default class List extends PureComponent {
  constructor(props) {
    super(props)
    this.state = {
      orderStatus: 0,
      noteVisible: false,
      actionVisible: false,
      actionType: '',
      orderList: [],
      currentOrder: {},
      loading: false,
      //搜索框选择的参数  类型为对象
      inputParams: null,
      //搜索框输入的值
      inputValue: '',
      //状态筛选值
      mainStatus: null,
      //筛选参数
      filterParams: {},
      //点击picker隐藏
      pickerVisible: false,
      //默认订单由近及远
      orderBy: 'desc',
      //picker的标题
      pickerTitle: '操作弹框',
      //取消订单的数据列
      cancelData: ORDER_LIST_CANCEL_REASON,
      //取消订单的选择原因
      cancelReason: '',
      //页面类型
      pageType: 'orderList',
      //按钮操作弹框显示隐藏
      buttonsActionVisible: false,
      webSocketIsOpen: false,
      restartOpenWebsoect: true,
      SocketTask: null,
      max_create_time: null, //秒时间戳
      Bscroll: null,
    }
  }

  //获取订单筛选参数
  getOrderParams = () => {
    const { inputParams, inputValue, mainStatus, filterParams, orderBy } = this.state

    let params = {
      order_type: 'normal'
    }

    if (inputParams && inputValue) {
      params[inputParams.value] = inputValue
    }

    if (mainStatus && mainStatus.value !== 'all') {
      params['main_status'] = mainStatus.value
    }

    if (orderBy) {
      params['order_by'] = orderBy
    }

    if (filterParams.orderClass) {
      if (filterParams.orderClass !== 'all') {
        params['order_class'] = filterParams.orderClass
      }
    }

    if (filterParams.receiptType) {
      params['receipt_type'] = filterParams.receiptType
    }

    if (filterParams.orderTime) {
      let timeArr = calculateTimestamp(filterParams.orderTime)
      if (timeArr.length) {
        params['time_start_begin'] = timeArr[0]
        params['time_start_end'] = timeArr[1]
      }
    }

    return params
  }

  searchFilter = async ({ isCMD, isResetList, isFirst }) => {
    let query = {}

    if (isFirst) {
      return
    }

    if (isCMD) {
      //如果是初始化
      query.orderList = []
      query.inputValue = ''
    }

    if (isResetList) {
      //筛选时需要置空
      query.orderList = []
    }
    // this.state.Bscroll.scrollTo(0,0,300)
    this.resetPage( async() => {
     this.setState(
        {
          ...this.state,
          ...query
        },
         async() => {
         await this.nextPage()
        }
      )
    })

  }

  async componentDidShow() {
    console.log('dianwu h5 comonentDidShow...')
    const {
      router: { params }
    } = getCurrentInstance()

    await this.searchFilter({ isCMD: true, isFirst: false })
  }
  handleTabClick = (activeIndex) => {
    this.setState({
      orderStatus: activeIndex
    })
  }

  //获取订单列表
  getOrdersList = async (params) => {

    let { distributor_id } = this.props.planSelection
    if (params.page_no == 1) {
      this.state.max_create_time = Math.trunc(calculateTimestamp('today')[1])
      console.log(timestampToTime(this.state.max_create_time))
    }
    const {
      list,
      pager: { count: total }
    } = await api.order.list({
      page: params.page_no,
      pageSize: params.page_size,
      distributor_id,
      max_create_time: this.state.max_create_time,
      ...this.getOrderParams()
    })

    this.setState({
      orderList: params.page_no > 1 ? [...this.state.orderList, ...list] : list
    })
    // this.state.Bscroll.refresh()
    return {
      total
    }
  }

  //请求
  fetch = async (params) => {
    this.setState({
      loading: true
    })
    console.log('-----fetch-----', params)
    const { total } = await this.getOrdersList(params)

    this.setState({
      loading: false
    })

    return { total }
  }

  //搜索参数变化回调
  handleParamChange = (inputParams) => {
    this.setState({
      inputParams: { ...inputParams }
    })
  }

  //值变化回调
  handleValueChange = (inputValue) => {
    this.setState({
      inputValue
    })
  }

  //状态变化的回调
  handleStatusChange = (status, init) => {
    this.setState({
      mainStatus: status
    })
    if (!init) {
      this.searchFilter({ isResetList: true })
    }
  }

  handleRefresh = () => {
    this.searchFilter({ isResetList: true })
  }

  //提交筛选状态
  handleSubmitParams = (params) => {
    this.setState({
      filterParams: params
    })
    console.log('1111')
    this.searchFilter({ isResetList: true })
  }

  //切换时间筛选
  orderClick = () => {
    const { orderBy } = this.state
    if (orderBy === 'desc') {
      this.setState(
        {
          orderBy: 'asc'
        },
        () => {
          this.searchFilter({ isResetList: true })
        }
      )
    } else {
      this.setState(
        {
          orderBy: 'desc'
        },
        () => {
          this.searchFilter({ isResetList: true })
        }
      )
    }
  }

  //点击商品列表
  handleClickGoodItem = (goodInfo) => {
    this.clearUnread(goodInfo.order_id)
    Taro.navigateTo({ url: `/pages/order/detail?order_id=${goodInfo.order_id}` })
  }

  clearUnread = async (order_id) => {
    const { type } = getCurrentInstance().router.params
    const obj = {
      distributor_id: this.props.planSelection.distributor_id,
      msg_type: 2,
      is_all_read: false,
      order_id,
    }
    await api.message.clearUnread(obj)
  }

  //点击操作按钮
  handleClickActionButtons = ({ order_id }, type) => {
    if (type == 'cancel') {
      // wx.miniProgram.navigateTo({
      //   url: `/subpages/dianwu/trade/cancel-trade?trade_id=${order_id}`
      // })
      //   const { orderInfo } = this.props
      //处理售后
      Taro.navigateTo({
        url: `/pages/order/cancel-trade/cancel-trade?trade_id=${order_id}`
      })
    } else if (type == 'aftersales') {
      // wx.miniProgram.navigateTo({
      //   url: `/subpages/dianwu/trade/sale-after?trade_id=${order_id}`
      // })
      Taro.navigateTo({
        url: `/pages/order/sale-after/sale-after?trade_id=${order_id}`
      })
    }
  }
  // //跳转到售后处理页
  // handleNavigationAftersalesDeal = () => {
  //   const { orderInfo } = this.props
  //   //处理售后
  //   Taro.navigateTo({
  //     url: `/pages/afterSales/deal?orderId=${orderInfo.order_id}`
  //   })
  // }

  // handleNavigationDeal = () => {
  //   const { orderInfo, maxOrderInfo } = this.props
  //   console.log('orderInfo', maxOrderInfo)
  //   //处理售后
  //   Taro.navigateTo({
  //     url: `/pages/afterSales/deal?aftersalesNo=${
  //       orderInfo.aftersales_bn || maxOrderInfo.aftersales_bn
  //     }`
  //   })
  // }

  //关闭操作弹框
  handleCloseActionButtons = () => {
    this.setState({
      buttonsActionVisible: false
    })
  }

  zitiWebsocket = () => {
    // const { id } = this.$instance.router.params
    const { webSocketIsOpen, restartOpenWebsoect, SocketTask } = this.state
    let { distributor_id } = this.props.planSelection
    let time = null
    // websocket 开始
    if (!webSocketIsOpen) {
      const token = S.getAuthToken()
      Taro.connectSocket({
        url: process.env.APP_WEBSOCKET,
        header: {
          'content-type': 'application/json',
          'token': `Bearer ${token}`,
          'sec-websocket-protocol': '1',
          'type': 'distributor',
          'distributor_id': distributor_id
        },
        success: function () {
          console.log('連接成功========connect success')
        }
      }).then((task) => {
        this.setState({
          SocketTask: task
        })
        task.onOpen(() => {
          console.log('打开成功========connect success')
          this.setState({
            webSocketIsOpen: true
          })
          task.send({ data: JSON.stringify({ 
            'token': `${token}`,
            'type': 'distributor',
            'user_id': distributor_id,
            "event":"save_client",}) 
          })
        })
        task.onError(() => {
          console.log('打开失败========connect error')
          this.setState({
            webSocketIsOpen: false
          })
        })
        task.onMessage((res) => {
          if (res.data === '401001') {
            S.toast('未登录，请登录后再试')
            this.setState(
              {
                webSocketIsOpen: false
              },
              () => {
                setTimeout(() => {
                  S.logout()
                  S.login()
                }, 700)
              }
            )
          } else {
            console.log(res)
            const message = JSON.parse(res.data)
            console.log(message)
            switch (message.trade_type) {
              case '0':
                break;
              case '1': {
                console.log(message.order_data)
                if (message.order_data) {
                  message.order_data['create_date'] = timestampToTime(message.order_data.items[0].create_time)
                  var array = [message.order_data]
                  const sever_order_status = {
                    // 'all': '全部',
                    'cancel': 'CANCEL',
                    'notpay': 'NOTPAY',
                    'ziti': 'PENDING',
                    'notship': 'PAYED',
                    'finish': 'DONE'
                  }
                  if (this.state.mainStatus && this.state.mainStatus.value !== 'all') {
                    if (message.order_data?.order_status == sever_order_status[this.state.mainStatus.value]) {
                      this.setState({
                        orderList: [...array, ...this.state.orderList]
                      })
                    }
                  } else {
                    console.log([...array, ...this.state.orderList])
                    this.setState({
                      orderList: [...array, ...this.state.orderList]
                    })
                  }
                  array = []
                  // clearTimeout(time)
                  //   time = setTimeout(() => {
                  //     this.searchFilter({ isResetList: false })
                  //     console.log('重新请求数据')
                  //   }, 700)
                }
              }
                break;
              default:
                break;
            }
          }
        })
        task.onClose(() => {
          this.setState({
            webSocketIsOpen: false
          })
          if (restartOpenWebsoect) {
            // this.restartOpenWebsocket()
          }
        })
      })
    }
  }

  restartOpenWebsocket = () => {
    const { restartOpenWebsoect } = this.state
    let { distributor_id } = this.props.planSelection
    this.setState(
      {
        restartOpenWebsoect: false
      },
      () => {
        const token = S.getAuthToken()
        Taro.connectSocket({
          url: process.env.APP_WEBSOCKET,
          header: {
            'content-type': 'application/json',
            'token': `Bearer ${token}`,
            'sec-websocket-protocol': '1',
            'type': 'distributor',
            'distributor_id': distributor_id
          },
          // header: {LF
          //   'content-type': 'application/json',
          //   'x-wxapp-session': token,
          //   'x-wxapp-sockettype': 'orderzitimsg'
          // },
          method: 'GET'
        }).then((task) => {
          this.setState({
            SocketTask: task
          })
          task.onOpen(() => {
            this.setState({
              restartOpenWebsoect: true
            })
          })
        })
      }
    )
  }
  async componentWillUnmount() {
    console.log('2222')
    if (this.state.SocketTask) {
      this.setState({
        restartOpenWebsoect: false
      })
      await this.state.SocketTask.close()
      this.setState = () => false
    }
  }
  componentDidMount() {
    this.zitiWebsocket()
  }
  onPullDownRefresh = async() => {
    // Tracker.dispatch('PAGE_PULL_DOWN_REFRESH')
    await this.searchFilter({ isResetList: false })

  }

  render() {
    const {
      orderList,
      page,
      loading,
      inputParams,
      inputValue,
      mainStatus,
      orderBy,
      pageType,
      buttonsActionVisible
    } = this.state
    const statusRecord = {
      pulling: '用力拉',
      canRelease: '松开吧',
      refreshing: '玩命加载中...',
      complete: '好啦',
    }
    return (
      <View>
        <SpNavBar title='订单列表' />
        <View className='page-order-list' style={getThemeStyle()}>
          <View className='sticky-header'>
            <View className='page-order-list-input'>
              <SelectInput
                inputParam={inputParams}
                inputValue={inputValue}
                pageType={pageType}
                paramChange={this.handleParamChange}
                valueChange={this.handleValueChange}
                onInputConfirm={this.searchFilter}
              />
            </View>

            <Tabbar
              pageType={pageType}
              mainStatus={mainStatus}
              statusChange={this.handleStatusChange}
            />

            <FilterBlock
              pageType={pageType}
              orderBy={orderBy}
              onResetListClick={this.onPullDownRefresh}
              onSubmitParams={this.handleSubmitParams}
              onOrderClick={this.orderClick}
            />
          </View>

          <PullToRefresh
            onRefresh={this.onPullDownRefresh}
            renderText={status => {
              return <div>{statusRecord[status]}</div>
            }}
          >
            <ScrollView
              scrollY
              className={classNames('wrapper', 'page-order-list-orderList', {
                ['show-buttonsaction']: buttonsActionVisible
              })}
              scrollWithAnimation
              // onScrollToLower={this.nextPage}
              // onScrollToUpper={this.onPullDownRefresh}
            >
              <View className='content' >
                {orderList.map((orderItem, index) => {
                  const buttons = orderItem?.app_info?.buttons.filter((btn) => btn.type != 'markdown' && btn.type != 'invoice')
                  return (
                    <SpOrderItem
                      key={`${orderItem.order_id}`}
                      pageType={pageType}
                      info={orderItem}
                      onGoodItemClick={this.handleClickGoodItem}
                      renderFooter={
                        <PageActionButtons
                          buttons={buttons}
                          pageType={pageType}
                          onClick={this.handleClickActionButtons.bind(this, orderItem)}
                          onClose={this.handleCloseActionButtons}
                          orderInfo={orderItem}
                          mainStatus={mainStatus}
                          onRefresh={this.handleRefresh}
                        />
                      }
                    />
                  )
                })}
                <InfiniteScroll loadMore={this.nextPage} hasMore={page.hasNext} />
                {/* {loading && <SpLoading>正在加载...</SpLoading>} */}

                {!page.isLoading && !page.hasNext && !orderList.length && (
                  <SpNote img='no_order.png'>暂时还没有您的订单信息</SpNote>
                )}

                {/* {!page.hasNext && !!orderList.length && <SpTips msg={'没有更多了哦~'}></SpTips>} */}
              </View>


            </ScrollView>
          </PullToRefresh>
          <SpToast />
        </View>
      </View>

    )
  }
}
